<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Console\Commands\WdtClient;
//测试执行命令  php artisan sync:SalesRefundPush
//接口描述：销售订单（包括发货前和发货后）退款或退货单据推送至ERP。注：销售订单的售后换货订单此接口推送“退货类型”退款单，换出订单“trade_push.php”推送
//文档地址: https://open.wangdian.cn/qyb/open/apidoc/doc?path=sales_refund_push.php

class SyncSalesRefundPush extends Command
{
    protected $signature = 'sync:SalesRefundPush';
    protected $description = '同步创建原始退款单数据到旺店通api';

    // 建议每间隔（5~10）分钟，将商城积累的退款单集中推送，每次请求不超过10单
    public function handle()
    {
        Log::info('同步任务SyncSalesRefundPush', ["开始推送退款单到旺店通"]);
        $sid = config('services.wdt.sid');
        $appkey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'sales_refund_push.php';

        $c = new WdtClient($sid, $appkey, $secret, $url);

        $batchSize = 10;
        $redisKey = 'refund:pending:push'; // 假设Redis列表名
        $total = Redis::llen($redisKey);

        while ($total > 0) {
            // 取出最多10条退款单
            $refunds = Redis::lrange($redisKey, 0, $batchSize - 1);
            if (empty($refunds)) {
                break;
            }

            $api_refund_list = [];
            foreach ($refunds as $refundJson) {
                $refund = json_decode($refundJson, true);
                if (!$refund) continue;
                // 这里假设退款单结构和官方文档一致
                $api_refund_list[] = $refund;
            }

            $c->putApiParam('api_refund_list', json_encode($api_refund_list, JSON_UNESCAPED_UNICODE));
            $result = $c->wdtOpenApi();
            Log::info('旺店通退款推送结果', [$result]);

            // 推送成功后移除（这里简单处理，实际可根据$result判断）
            Redis::ltrim($redisKey, $batchSize, -1);
            $total = Redis::llen($redisKey);
        }

        $this->info('退款单推送任务执行完毕');
    }
} 